package com.ingenio.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.business.Proveedor;
import com.ingenio.dao.ProveedorAdapter;

/**
 * Servlet implementation class ObtenerProveedorServlet
 */
@WebServlet("/ObtenerProveedor")
public class ObtenerProveedorServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ObtenerProveedorServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			JSONObject json = new JSONObject();
			if("buscaCod".equals(request.getParameter("tipo"))){
				if(request.getParameter("id") != ""){
					ProveedorAdapter pa = new ProveedorAdapter();
					Integer id = Integer.parseInt(request.getParameter("id"));
					Proveedor p = pa.devolverProveedor(id);
					
					if(p != null){
						json.put("descripcion", p.getDescProveedor());
					}else{
						json.put("error","error");
					}
				}else{
					json.put("error","error");
				}
			}else{
				if("buscaDesc".equals(request.getParameter("tipo"))){
					if(request.getParameter("desc") != ""){
						ProveedorAdapter pa = new ProveedorAdapter();
						String descripcion = request.getParameter("desc");
						List<Proveedor> provs = pa.buscarProveedor(descripcion);
						JSONArray ja = new JSONArray();
						
						for (Proveedor p : provs) {
						   JSONObject jo = new JSONObject();
						   jo.put("id", p.getIdProvedoor());
						   jo.put("desc", p.getDescProveedor());
						   ja.put(jo);
						}
						
						json.put("proveedores", ja);
					}else{
						json.put("error","error");
					}
				}
			}
			response.setContentType("application/json");
			response.getWriter().write(json.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
